package resources 
{
	import app.textures.TexturePartInfo;
	import flash.display.BitmapData;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;
	import tasks.LoadResource;
	import utils.ErrorsCollector;
	import utils.Logger;
	/**
	 * ...
	 * @author Dmitriy Gaiduk
	 */
	
	 /**
	  * Dispatch when load textures complete
	  */
	[Event(name = "complete", type = "flash.events.Event")]
	public class TextureParts extends EventDispatcher implements  IBitmapDataProvider
	{
		private var _bmDictionary:Dictionary;
		private var _loadTasks:Vector.<LoadResource>;
		private var _taskCompleted:int;
		
		public function TextureParts() 
		{
			_bmDictionary = new Dictionary();
		}
		
		public function getBitmapData(bitmapID:String):BitmapData
		{
			var bmData:BitmapData;
			bmData = _bmDictionary[bitmapID] as BitmapData;
			if (bmData != null)
			{
				//return bmData.clone();
				return bmData.clone();
			}
			return null;
		}
		
		/**
		 * Если текстура загружена, то она не будет загружаться
		 * @param	partsInfoArray
		 */
		public function loadTextures(partsInfoArray:Vector.<TexturePartInfo>):void
		{
			if (_loadTasks != null)
			{
				log("loadTasks not null!!!");
				return;
			}
			
			_loadTasks = new Vector.<LoadResource>();
			var task:LoadResource;
			
			// 
			var bmDataForCheck: BitmapData;
			for each(var partInfo:TexturePartInfo in partsInfoArray)
			{
				bmDataForCheck = _bmDictionary[partInfo.sizeType] as BitmapData;
			
				if (bmDataForCheck == null)
				{
					task = new LoadResource(partInfo.url, partInfo.sizeType);
					
					_loadTasks.push(task);
					task.addEventListener(Event.CHANGE, handleTaskComplete);
				}
			}
			
			_taskCompleted = 0;
			if (_loadTasks.length == 0)
			{
				_loadTasks = null;
				dispatchEvent(new Event(Event.COMPLETE));
			}
			for each(task in _loadTasks)
			{
				task.run();
			}
		}
		
		private function handleTaskComplete(e:Event):void 
		{
			// make bitmapdata
			var task:LoadResource = e.currentTarget as LoadResource;
			if (task == null)
			{
				log("task null: " + e.currentTarget);
				return;
			}
			
			if (task.ready && task.loader != null)
			{
				var bmData:BitmapData = new BitmapData(task.loader.width, task.loader.height, false, 0xFF0000);
				bmData.draw(task.loader);
				_bmDictionary[task.userTag] = bmData;
			}else
			{
				log("File not found: " + task.url);
			}
			task.destroy();
			_taskCompleted++;
			
			if (_taskCompleted == _loadTasks.length)
			{
				//completeLoad
				_loadTasks.splice(0, _loadTasks.length);
				_taskCompleted = 0;
				dispatchEvent(new Event(Event.COMPLETE));
				_loadTasks = null;
			}
		}
		
		public function dispose():void
		{
			if (_loadTasks != null)
			{
				log("Cant dispose: current task not completed");
				return;
			}
			
			// clear bitmaps
			var keys:Vector.<Object> = new Vector.<Object>();
			var key:Object;
			for (key in _bmDictionary) 
			{
			  var bmData:BitmapData = _bmDictionary[key] as BitmapData;
			  if (bmData != null)
			  {
				bmData.dispose();
			  }else
			  {
				  log("Wrong data in BitmapData Dictionary: " + _bmDictionary[key]);
			  }
			  keys.push(key);
			}
			
			// clear keys
			for each (key in keys)
			{
				_bmDictionary[key] = null;
				delete _bmDictionary[key];
			}
			
			_bmDictionary = null;
			keys.splice(0, keys.length);
			keys = null;
			log("Disposed");
		}
		
		private function handleError(msg:String):void
		{
			ErrorsCollector.collectError(msg);
		}
		
		private function log(msg:String):void
		{
			Logger.log(this, msg);
		}
	
		
	}

}